package regex;


import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import utils.Log;
import utils.StringUtils;

import java.util.regex.*;

/**
 * Created by shane on 2018/8/19.
 *
 * refs: http://www.runoob.com/java/java-regular-expressions.html
 *
 */
public class HelloRegex {

    private static final String URL_PATTERN = "((http|https)://)?(((25[0-5]|2[0-4]\\d|[01]?\\d\\d?)\\.){3}(25[0-5]|2[0-4]\\d|[01]?\\d\\d?)|([a-zA-Z0-9_\\-\\.]+\\.[a-zA-Z]{2,6}))([-a-zA-Z0-9:%;_\\+'~#?&//=\\(\\)\\[\\]\\.]*)?[-a-zA-Z0-9:%;_\\+'~#?&//=\\(\\)\\[\\]]";

    static final String HOST_PATTERN = "(.*\\.hutaojie\\.com)|(.*\\.yangkeduo\\.com)|(.*\\.pdd\\.net)|(.*\\.yiran\\.com)";
    static Pattern sPattern;
    static Pattern sPhonePattern = Pattern.compile("86[-]?1[0-9]{10}");
    static Pattern sHostPattern = Pattern.compile(HOST_PATTERN);

    static {
        sPattern = Pattern.compile(URL_PATTERN);
    }

    public static void main(String[] args) {

        Log.vn("isValidHost, host:" + HOST_PATTERN);
        isValidHost("file.hutaojie.com");
        isValidHost("file2.hutaojie.com");
        isValidHost("file2hutaojie.com");
        isValidHost("file2.yangkeduo.com");
        isValidHost("file2.pdd.net");
        isValidHost("api-knock.htj.pdd.net");
        // test2();
        // new SJPatternTest().test();
        //new SJPatternTest2().test();
        List<String> wordList = new ArrayList<>();
        wordList.add("风润");
        wordList.add("石");

        if (true) {
            String snippet = updateSnippetBySearchWord("风润、石送、将军", wordList);
            Log.vn("snippet:" + snippet);

            indexOfAt("12@fengrun\7");
            return;
        }


        indexOfUrl("您好，风润，您于2019-09-22 10:54:05 打卡成功，若要关闭打卡提醒，可点击https://oa.pdd.net/apply?calendar=open关闭“打卡邮件提醒”。");
        indexOfUrl("我怎么感觉点knock ios的图标，有的时候，感觉会卡个0.x秒，大家有碰到这个情况不？");
        indexOfUrl("https://gitlab.hutaojie.com/pdd_merchant/pdd-im-android/merge_requests/2340/diffs  你好， 电话是15911025590");

    }

    static void isValidHost(String host) {
        boolean res = sHostPattern.matcher(host).matches();
        Log.vn("isValidHost, host:" + host + ", res:" + res);
    }

    static void indexOfAt(String text) {
        //Log.vn(UrlUtils.indexOfUrl(text));
        Log.vn(AtUtils.indexOfAt(text));
        // Log.vn(UrlUtils2.indexOfUrl(text));
    }

    static void indexOfUrl(String text) {
        //Log.vn(UrlUtils.indexOfUrl(text));
        Log.vn(UrlUtils.indexOfPhone(text));
        // Log.vn(UrlUtils2.indexOfUrl(text));
    }

    static void test2() {
        String url1 = "https://ant-console.corp.yiran.com/manageToB/download";
        String url2 = "https2://ant-console.corp.yiran.com/manageToB/download";

        Log.vn(String.format("content:%s, res:%b", url1, sPattern.matcher(url1).matches()));
        Log.vn(String.format("content:%s, res:%b", url2, sPattern.matcher(url2).matches()));
    }


    static void test() {
        String content = "I am noob " +
            "from runoob.com.";

        String pattern = ".*runoob.*";

        boolean isMatch = Pattern.matches(pattern, content);
        Log.vn("字符串中是否包含了 'runoob' 子字符串? " + isMatch);


        pattern = "^[a-z][a-z0-9][a-zA-Z0-9]*$";

        isMatch(pattern, "mView");
        isMatch("^[a-z][a-zA-Z0-9]*$", "mView");
        isMatch("zo+", "zooo");
        isMatch("^[a-z][a-z0-9]", "2boo");
        isMatch("^[a-z][a-z0-9]", "zboo");
        isMatch("^[a-z][a-z0-9]", "zb");
        isMatch("^[a-z][a-z0-9]", "zBoo");

        isMatch("[a-zA-Z0-9]*$", "zBoo");
        isMatch("[a-zA-Z0-9]*$", "zboo");
        isMatch("[a-zA-Z0-9]*$", "z@oo");

        String url = "https://mms.pinduoduo.com/chats/users/${uid}";
        String REQ_RESTFUL_FORMATTER = "${%s}";
        String REQ_RESTFUL_REPLACE_FORMATTER = "${%s}";
        String uid = "uid";
        String realKey = String.format(REQ_RESTFUL_FORMATTER, uid);
        // https://stackoverflow.com/questions/17462146/java-patternsyntaxexception-illegal-repetition-on-string-substitution
        String val = "5057038763591";
        if (url.indexOf(realKey) >= 0) {
            url = url.replaceAll(Pattern.quote(realKey), val);
            Log.vn(url);
        }
    }


    public static boolean isMatch(String pattern, String content) {
        if (StringUtils.isEmpty(pattern) || StringUtils.isEmpty(content)) {
            return false;
        }

        boolean res = false;
        try {
            res = Pattern.matches(pattern, content);
            Log.vn(String.format("pattern:%s, content:%s, res:%b", pattern, content, res));
        } catch (Throwable tr) {
            tr.printStackTrace();
        }

        return res;
    }


    /**
     * 通配搜索出来高亮是整个 word，所以需要手动对高亮的长度根据搜索词进行调整
     * @param snippet
     * @param wordList
     * @return
     */
    private static String updateSnippetBySearchWord(String snippet, List<String> wordList) {
        // 按长度逆序排列
        Collections.sort(wordList, (o1, o2) -> o2.length() - o1.length());
        StringBuilder result = new StringBuilder(snippet);
        for (String word : wordList) {
            if (word.isEmpty()) {
                continue;
            }
            word = word.toLowerCase();

            int startIndex = 0;
            int endIndex = 0;
            while (startIndex >= 0 && endIndex >= 0) {
                String currentResult = result.toString().toLowerCase();
                startIndex = currentResult.indexOf(CharUtils.getInvisibleChar1() + word, endIndex);
                endIndex = currentResult.indexOf(CharUtils.getInvisibleChar2() + "", startIndex);

                if (startIndex < 0 || endIndex < 0) {
                    continue;
                }
                // 匹配长度和时间长度不一致
                boolean updated = false;
                if (endIndex - startIndex - 1 > word.length()) {
                    // 判断是否之前修改过
                    for (String wordItem : wordList) {
                        String item = CharUtils.getInvisibleChar1() + wordItem + CharUtils.getInvisibleChar2();
                        if (item.equalsIgnoreCase(result.substring(startIndex, endIndex + 1))) {
                            updated = true;
                            break;
                        }
                    }
                    if (updated) {
                        continue;
                    }

                    // 调整 snippet 的高亮位置
                    // 删除 end 位置
                    result.deleteCharAt(endIndex);
                    // 在关键词长度位置处加上 end 标记
                    result.insert(startIndex + word.length() + 1, CharUtils.getInvisibleChar2());
                }
            }
        }
        return result.toString();
    }
}
